package me.zhengjie.modules.security.security;

import me.zhengjie.modules.security.utils.GeoLocationUtil;
import me.zhengjie.modules.website.domain.AccessLogs;
import me.zhengjie.modules.website.repository.AccessLogsRepository;
import me.zhengjie.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

@Component
public class AccessLogInterceptor implements HandlerInterceptor {

    @Autowired
    private AccessLogsRepository accessLogRepository;

    @Autowired
    private GeoLocationUtil geoLocationUtil;  // 引入 GeoLocationUtil

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取客户端 IP 地址
        String ipAddress = request.getRemoteAddr();

        // 获取访问页面的 URL
        String page = request.getRequestURI();

        // 获取地理位置（城市）
        //String location = geoLocationUtil.getLocationByIp(ipAddress);
        String location = StringUtils.getCityInfo(ipAddress);

        // 创建访问记录对象
        AccessLogs accessLog = new AccessLogs();
        accessLog.setIpAddress(ipAddress);
        accessLog.setVisitTime(LocalDateTime.now());
        accessLog.setPage(page);
        accessLog.setLocation(location);

        // 将访问记录保存到数据库
        accessLogRepository.save(accessLog);

        // 返回 true，表示继续处理请求
        return true;
    }
}

